package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.common.Result;

import com.example.demo.entity.Role;
import com.example.demo.entity.RolePermission;
import com.example.demo.mapper.PermissionMapper;
import com.example.demo.service.RoleService;
import io.swagger.annotations.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import com.example.demo.entity.Permission;
import com.example.demo.mapper.RoleMapper;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags="角色管理接口")
@RestController
@RequestMapping("/role")
//@CrossOrigin(origins = "*")
public class RoleController {
    @Resource
    RoleMapper roleMapper;

    @Resource
    private RoleService roleService;

    @Resource
    private PermissionMapper permissionMapper;

    @PreAuthorize("hasAuthority('sys:role:add')")
    @ApiOperation(value = "增加角色", notes = "增加一个新角色")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "增加角色成功"),
            @ApiResponse(code = 401, message = "添加角色失败")
    })
    @PostMapping("addRole")
    public Result addRole(@RequestBody Role role){
        int res = roleService.addRole(role);
        if(res != 0){
            return Result.success("增加角色成功");
        }else{
            return Result.error("401","添加角色失败");
        }
    }

    @PreAuthorize("hasAuthority('sys:role:edl')")
    @ApiOperation(value = "删除角色", notes = "删除指定角色")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "删除角色成功"),
            @ApiResponse(code = 401, message = "删除角色失败")
    })
    @DeleteMapping("delRole")
    public Result delRole(Integer roleId){
        int res = roleService.delRole(roleId);
        if(res != 0){
            return Result.success("删除角色成功");
        }else{
            return Result.error("401","删除角色失败");
        }
    }


    //@PreAuthorize("hasAuthority('sys:permission:add')")
    @ApiOperation(value = "增加角色权限", notes = "为指定角色增加一个新权限")
    @ApiImplicitParam(name = "permissionId", value = "权限ID", required = true, dataType = "int", paramType = "query")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "添加角色权限成功"),
            @ApiResponse(code = 401, message = "添加角权限失败")
    })
    @PostMapping("addRolePermission")
    public Result addRolePermission(@RequestBody Role role, Integer permissionId){
        int res = roleService.addRolePermission(role, permissionId);
        if(res != 0){
            return Result.success("添加角色权限成功");
        }else{
            return Result.error("401","添加角权限失败");
        }
    }



    //@PreAuthorize("hasAuthority('sys:permission:del')")
    @ApiOperation(value = "删除角色权限", notes = "在系统中删除指定角色的指定权限")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "删除角色权限成功"),
            @ApiResponse(code = 401, message = "删除角色权限失败")
    })
    @DeleteMapping("delRolePermission")
    public Result delRolePermission(RolePermission rolePermission) {
        int res = roleService.delRolePermission(rolePermission);
        if (res != 0) {
            return Result.success("删除角色权限成功");
        } else {
            return Result.error("401", "删除角色权限失败");
        }
    }


    //@PreAuthorize("hasAuthority('sys:role:get')")
    @ApiOperation(value = "获取角色列表", notes = "获取角色列表")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "获取角色列表成功"),
            @ApiResponse(code = 401, message = "获取角色列表失败"),
            @ApiResponse(code = 500, message = "服务器错误")
    })
    @GetMapping("getRoles")
    public Result getRoles(){
        List<Role> roles=roleService.selectAllRoles();
        List<Map<String,Object>> res=new ArrayList<>();
        for(Role role:roles){
            Map<String,Object> map=new HashMap<>();
            map.put("roleId",role.getRoleId());
            map.put("roleLabel",role.getRoleLabel());
            map.put("status",role.getStatus());
            List<Permission> permissions= roleMapper.selectPermissionsByRoleId(role.getRoleId());
            map.put("permissions",permissions);
            res.add(map);
        }
        return Result.success(res);
    }

    //@PreAuthorize("hasAuthority('sys:permission:get')")
    @ApiOperation(value = "获取权限", notes = "通过角色ID获取权限")
    @ApiImplicitParam(name = "roleId", value = "角色ID", required = true, dataType = "int", paramType = "query")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "获取权限成功"),
            @ApiResponse(code = 401, message = "获取权限失败"),
            @ApiResponse(code = 500, message = "服务器错误")
    })
    @GetMapping("getPermissions")
    public Result getPermissions(Integer roleId){
        List<Permission> res= roleMapper.selectPermissionsByRoleId(roleId);
        return Result.success(res);
    }

    @PreAuthorize("hasAuthority('sys:permission:edit')")
    @ApiOperation(value = "修改角色权限", notes = "通过角色ID修改权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色ID", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "permissionId", value = "权限ID", required = true, dataType = "MyArray", paramType = "query")
    })
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "修改权限成功"),
            @ApiResponse(code = 401, message = "修改权限失败"),
            @ApiResponse(code = 500, message = "服务器错误")
    })
    @PostMapping("editRolePermission")
    public Result editRolePermission(Integer roleId,@RequestBody Integer[] permissionId){
        Integer res=roleService.saveOrUpdate(roleId,permissionId);
        if(res==1){
            return Result.success("修改成功");
        }else{
            return Result.error("401","修改失败");
        }
    }

    @ApiOperation(value = "获取权限列表")
    @ApiResponse(code = 500, message = "获取失败")
    @GetMapping("/getPermissionList")
    public Result getPermissionList(){
        QueryWrapper<Permission> baseQueryWrapper=new QueryWrapper<>();
        baseQueryWrapper.eq("pid",0);
        List<Permission> permissionBase=permissionMapper.selectList(baseQueryWrapper);
        QueryWrapper<Permission> notBaseQueryWrapper=new QueryWrapper<>();
        notBaseQueryWrapper.ne("pid",0);
//      notBaseQueryWrapper.ne("pid",null);
        List<Permission> permissionNotBase=permissionMapper.selectList(notBaseQueryWrapper);
        for(Permission permission:permissionBase){
            List<Permission> permissions=roleService.iteratePermission(permissionNotBase,permission.getPermissionId());
            permission.setChildren(permissions);
        }
        if(permissionBase!=null){
            return Result.success(permissionBase);
        }else{
            return Result.error("500","未能获取权限列表");
        }
    }

    @ApiOperation(value = "修改角色")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "修改成功"),
            @ApiResponse(code = 500, message = "修改失败")
    })
    @PutMapping("/editRole")
    public Result editRole(@RequestBody Role role){
        int res=roleService.updateRole(role);
        if(res==1){
            return Result.success("修改角色成功");
        }else{
            return Result.error("500","修改失败");
        }
    }
}

